// ===================================
// <copyright>LogoUI Co.</copyright>
// <author>Vlad Spivak</author>
// <email>mailto:vlads@logoui.co.il</email>
// <created>06/00/11</created>
// <lastedit>06/00/11</lastedit>

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
// <remarks>Part of this software based on various internet sources, mostly on the works
// of members of Wpf Disciples group http://wpfdisciples.wordpress.com/
// Also project may contain code from the frameworks: 
//        Nito - http://nitokitchensink.codeplex.com/
//        OpenLightGroup - http://openlightgroup.net/
//        nRoute - http://nroute.codeplex.com/
//        SilverlightFX - http://projects.nikhilk.net/SilverlightFX
//        BlackLight - http://blacklight.codeplex.com/
// </remarks>
// ====================================================================================//

#if !SILVERLIGHT

namespace System.ComponentModel
{
    public class DelegatingTypeDescriptorProvider : TypeDescriptionProvider
    {
        private readonly DelegatingTypeDescriptor m_ed;

        public DelegatingTypeDescriptorProvider(object owner, object target, TypeDescriptionProvider parent):this(owner,target,parent,true)
        {
        }

        public DelegatingTypeDescriptorProvider(object owner, object target, TypeDescriptionProvider parent, bool allowDuplicatedNames):this(owner,target,parent,allowDuplicatedNames,null)
        {
        }

        public DelegatingTypeDescriptorProvider(object owner, object target, TypeDescriptionProvider parent, bool allowDuplicatedNames, Attribute[] attr)
            : base(parent)
        {
            m_ed = new DelegatingTypeDescriptor(owner, target, allowDuplicatedNames,attr); 
        }
        public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
        {
            return m_ed;
        }
        
        public object Owner
        {
            get
            {
                return m_ed.Owner;
            }
        }
    }

    public class DelegatingTypeDescriptor : CustomTypeDescriptor
    {
        private readonly WeakReference m_owner;

        readonly PropertyDescriptorCollection m_pdc = new PropertyDescriptorCollection(null);
        public DelegatingTypeDescriptor(object owner, object target, Attribute[] attr) : this(owner, target, true, attr) { }
        public DelegatingTypeDescriptor(object owner, object target) : this(owner, target, true, null) { }
        public DelegatingTypeDescriptor(object owner, object target,bool allowDuplicatedNames,Attribute[] attr)
            : base(TypeDescriptor.GetProvider(target).GetTypeDescriptor(target))
        {

            m_owner = new WeakReference(owner,false);
            //todo:owner.GetType() is not exact one. Exact one is owner instance itself,but currently
            //todo:it will be the huge performance impact due to Attached Dependancy Properties reevaluation
            foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(owner.GetType(), new Attribute[] { BrowsableAttribute.Default }))
            {
                m_pdc.Add(pd);
            }
            PropertyDescriptorCollection pdc;
#if !useattr
            if (attr == null)
                pdc = base.GetProperties();
            else

                pdc = base.GetProperties(attr);
#else

            pdc = base.GetProperties(new Attribute[] {BrowsableAttribute.Yes, BrowsableAttribute.No});
#endif
            foreach (PropertyDescriptor pd in pdc)
            {
                if (!allowDuplicatedNames && m_pdc[pd.Name] != null)
                {
                    int i = 0;
                    while (m_pdc[pd.Name + "_" + i] != null) i++;
                    m_pdc.Add(new DelegatingPropertyDescriptor(target, pd, pd.Name + "_" + i));
                }
                else
                {
                    m_pdc.Add(new DelegatingPropertyDescriptor(target, pd));
                }
            }
        }

        public object Owner
        {
            get
            {
                return m_owner.Target;
            }
        }

        public override PropertyDescriptorCollection GetProperties()
        {
            return m_pdc;
        }
        public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
        {
            return m_pdc;
        }
    }

    /// <summary>
    /// Delegates metadate to foreign object
    /// </summary>
    public class DelegatingPropertyDescriptor:PropertyDescriptor,ICustomTypeDescriptor
    {
        private readonly WeakReference m_source;
        private readonly PropertyDescriptor m_orig;
        public DelegatingPropertyDescriptor(object source,PropertyDescriptor prdesk)
            : this(source, prdesk,null)
        {
        }
        public DelegatingPropertyDescriptor(object source, PropertyDescriptor prdesk, string newname)
            : base(newname??prdesk.Name, null)
        {
            m_source = new WeakReference(source);
            m_orig = prdesk;
        }

        public override bool CanResetValue(object component)
        {
            return true;
        }

        public override object GetValue(object component)
        {
            return m_source.IsAlive?WrappedDescriptor.GetValue(m_source.Target):null;
        }

        public override void ResetValue(object component)
        {
            if (m_source.IsAlive)
                WrappedDescriptor.ResetValue(m_source.Target);
        }

        public override void SetValue(object component, object value)
        {
            if (m_source.IsAlive)
                WrappedDescriptor.SetValue(m_source.Target, value);
        }

        public override bool ShouldSerializeValue(object component)
        {
            return m_source.IsAlive?WrappedDescriptor.ShouldSerializeValue(m_source.Target):false;
        }

        public override Type ComponentType
        {
            get
            {
                return m_source.IsAlive?m_source.Target.GetType():null;
            }
        }

        public override bool IsReadOnly
        {
            get { return WrappedDescriptor.IsReadOnly; }
        }

        public override Type PropertyType
        {
            get { return WrappedDescriptor.PropertyType; }
        }

        public PropertyDescriptor WrappedDescriptor
        {
            get { return m_orig; }
        }

        #region ICustomTypeDescriptor Members

        AttributeCollection ICustomTypeDescriptor.GetAttributes()
        {
            return TypeDescriptor.GetAttributes(WrappedDescriptor);
        }

        string ICustomTypeDescriptor.GetClassName()
        {
            return TypeDescriptor.GetClassName(WrappedDescriptor);
        }

        string ICustomTypeDescriptor.GetComponentName()
        {
            return TypeDescriptor.GetComponentName(WrappedDescriptor);
        }

        TypeConverter ICustomTypeDescriptor.GetConverter()
        {
            return TypeDescriptor.GetConverter(WrappedDescriptor);
        }

        EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
        {
            return TypeDescriptor.GetDefaultEvent(WrappedDescriptor);
        }

        PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
        {
            return TypeDescriptor.GetDefaultProperty(WrappedDescriptor);
        }

        object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
        {
            return TypeDescriptor.GetEditor(WrappedDescriptor,editorBaseType);
        }

        EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
        {
            return TypeDescriptor.GetEvents(WrappedDescriptor, attributes);
        }

        EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
        {
            return TypeDescriptor.GetEvents(WrappedDescriptor);
        }

        PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
        {
            return TypeDescriptor.GetProperties(WrappedDescriptor, attributes);
        }

        PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
        {
            return TypeDescriptor.GetProperties(WrappedDescriptor);
        }

        object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
        {
            return WrappedDescriptor;
        }

        #endregion
        public override string ToString()
        {
            return "-> " + WrappedDescriptor;
        }
    }

}
#endif